// 未调试
#include <bits/stdc++.h>
using namespace std;
int a[200005];
int dp[2005][2005];    // dp[i][j]表示排序区间[i,j]的最小花费
int maxxd[2005][2005]; // maxxd[i][j]表示区间[i,j]的最大值
int minn[2005][2005];  // minn[i][j]表示区间[i,j]的最小值

int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }

  // 预处理maxxd和minn数组
  for (int i = 1; i <= n; i++) {
    maxxd[i][i] = a[i];
    minn[i][i] = a[i];
    for (int j = i + 1; j <= n; j++) {
      maxxd[i][j] = max(maxxd[i][j - 1], a[j]);
      minn[i][j] = min(minn[i][j - 1], a[j]);
    }
  }

  // 区间DP初始化
  for (int len = 1; len <= n; len++) {
    for (int i = 1; i + len - 1 <= n; i++) {
      int j = i + len - 1;
      if (len == 1) {
        dp[i][j] = 0; // 单个元素不需要排序
      } else {
        // 使用预处理好的maxxd和minn
        dp[i][j] = maxxd[i][j] - minn[i][j]; // 直接排序整个区间
        for (int k = i; k < j; k++) {
          dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]);
        }
      }
    }
  }

  cout << dp[1][n];
  return 0;
}